import 'package:chewie/chewie.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_ncsjqz_getx/api/api.dart';
import 'package:flutter_ncsjqz_getx/constant/constant.dart';
import 'package:flutter_ncsjqz_getx/http/dio_service.dart';
import 'package:flutter_ncsjqz_getx/model/base_entity.dart';
import 'package:flutter_ncsjqz_getx/model/post_detail_entity.dart';
import 'package:flutter_ncsjqz_getx/util/7niu_util.dart';
import 'package:flutter_ncsjqz_getx/util/toast_util.dart';
import 'package:flutter_ncsjqz_getx/widget/bottom_sheet_widget.dart';
import 'package:flutter_ncsjqz_getx/widget/ink_widget.dart';
import 'package:get/get.dart';
import 'package:video_player/video_player.dart';

class GuangChangDetailsLogic extends GetxController {
  String? hfUser;
  int? hfUserId;
  int? hfId;
  PostDetailData?  circleDetailData = PostDetailData();
  TextEditingController textEditingController = TextEditingController();
  TextEditingController textEditingControllerJuBao = TextEditingController();
  ScrollController scrollController = ScrollController();
  int? postId;
  List<Widget> fileList = [];
  List<ImageVideoPickModel> pickList = [];
  List<String> imgs = [];
  int count = 0;
  ChewieController? chewieController;
  VideoPlayerController? videoPlayerController1;

  getPlay(url) async{
    // player!.setDataSource(url ?? Api.testVideo1,showCover: true);
    videoPlayerController1 = VideoPlayerController.network(url ?? Api.testVideo1);
    await videoPlayerController1!.initialize();
    chewieController = ChewieController(
      videoPlayerController: videoPlayerController1!,
      autoPlay: false,
      looping: true,
      showOptions: false,
    );
    update();
  }

  setListOut(){
    scrollController.animateTo(
      scrollController.position.maxScrollExtent, //滚动位置
      curve: Curves.easeOut, //动画效果
      duration: const Duration(milliseconds: 300), //动画时间
    );
    update();
  }

  getCount(){
    count = circleDetailData!.comments!.length;
    circleDetailData!.comments!.forEach((element) {
      count+=element.replys!.length;
    });
    update();
  }

  postDetail() async {
    Map<String, dynamic> data = {
      "postId": postId,
    };
    PostDetailEntity circleDetailEntity = await DioService<PostDetailEntity>().postDetail(data);
    if(circleDetailEntity.code == 0){
      circleDetailData = circleDetailEntity.data;
      if(circleDetailData!.postVideos != null && circleDetailData!.postVideos!.length>0){
        getPlay(circleDetailData!.postVideos![0]);
      }
      getCount();
      update();
    }else{
      Get.back();
    }
  }

  /// 投诉
  complaint() async {
    if(imgs.length == 0) return toast("未上传图片证据");
    if(textEditingControllerJuBao.text == "") return toast("未输入投诉内容");
    Map<String, dynamic> data = {
      "beUserId": circleDetailData!.userId,
      "complaintDetail": textEditingControllerJuBao.text,
      "complaintTitle": textEditingControllerJuBao.text,
      // "complaintType": 0,
      // "complaintTypeId": 0,
      "complaintUrls": imgs,
      "postId": circleDetailData!.postId,
      "userId": Constant.userDetailData!.id,
    };
    BaseEntity baseEntity = await DioService<BaseEntity>().complaint(data);
    if(baseEntity.code == 0){
      imgs = [];
      fileList = [];
      pickList = [];
      textEditingControllerJuBao.text = "";
      fileList.insert(fileList.length, selectAddBtn());
      toast("投诉成功");
      Get.back();
      update();
    }
  }

  /// 文件上传
  Future<Null> uploadFile(path) async{
    await Niu7Util.instance!.upload(path,onUrl: (v){
      imgs.add(v);
    });
    update();
  }

  /// 回复
  publishReply() async{
    if(textEditingController.value.text == "") return toast("不能回复空内容");
    Map<String, dynamic> data = {
      "beReplyUserId": hfUserId,
      "commentId": hfId,
      "replyContent": textEditingController.value.text,
      "replyUserId": Constant.userDetailData!.id,
    };
    BaseEntity baseEntity = await DioService<BaseEntity>().publishReply(data);
    if(baseEntity.code == 0){
      toast("回复成功");
      postDetail();
      textEditingController.text = "";
      hfId = null;
      hfUser = null;
      hfUserId = null;
    }
    update();
  }

  /// 评论
  publishComment(postId,userId)async{
    if(textEditingController.value.text == "") return toast("不能发表空评论");
    Map<String, dynamic> data = {
      "commentContent": textEditingController.value.text,
      "commentUserId": Constant.userDetailData!.id,
      "postId": postId,
      "replyUserId": userId,
    };
    BaseEntity baseEntity = await DioService<BaseEntity>().publishComment(data);
    if(baseEntity.code == 0){
      toast("评论发表成功");
      postDetail();
      textEditingController.text = "";
    }
    update();
  }

  /// 图片选择按钮
  Widget selectAddBtn(){
    return InkWell(
      child: ClipRRect(
        borderRadius: BorderRadius.circular(5),
        child: Container(
          width: (Get.width - 30 - 30) / 3,
          height: (Get.width - 30 - 30) / 3,
          color: Colors.grey.shade200,
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Icon(Icons.add_circle,color: Colors.grey,size: 40,),
              InkWidget.text("点击上传",color: Colors.grey),
            ],
          ),
        ),
      ),
      onTap: (){
        BottomSheetWidget.bottomImagePickWidget(
            callBack: (v) async{
              Get.back();
              if(v.length>0){
                await uploadFile(v[0].path);
                fileList = [];
                for(int i=0;i<imgs.length;i++){
                  fileList.add(imageAdd(imgs[i],i));
                }
                if(imgs.length < 9){
                  fileList.insert(fileList.length, selectAddBtn());
                }
                update();
              }
            },
          selectCount: 9 - imgs.length
        );
      },
    );
  }

  /// 选择的图片
  Widget imageAdd(url,index){
    return InkWell(
      child: Stack(
        children: [
          ClipRRect(
            borderRadius: BorderRadius.circular(5),
            child: Container(
              width: (Get.width - 30 - 30) / 3,
              height: (Get.width - 30 - 30) / 3,
              color: Colors.grey.shade200,
              child: InkWidget.imgNet("$url"),
            ),
          ),
          Positioned(
            top: 0,
            right: 0,
            child: InkWell(
              child: Icon(Icons.highlight_remove,color: Colors.red,size: 40,),
              onTap: (){
                print(index);
                fileList.removeAt(index);
                imgs.removeAt(index);
                update();
              },
            ),
          )
        ],
      ),
      onTap: (){
      },
    );
  }
}
